package com.uduew.sjd.ui.repayment

import android.os.Bundle
import android.view.View
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.uduew.sjd.api.AllLoanOrdersApi
import com.uduew.sjd.bean.CustomerBean
import com.uduew.sjd.message.Messages
import com.uduew.sjd.message.PageMessenger
import com.uduew.sjd.net.DataResult
import com.uduew.sjd.request.RepaymentRequester
import com.uduew.sjd.ui.adapter.RepaymentAdapter
import com.uduew.sjd.ui.base.BaseFragment
import com.uduew.sjd.ui.base.StateHolder
import com.uduew.sjd.utils.ToastUtils
import com.uduew.sjd.utils.Utils
import com.uduew.sjd.view.xpop.CustomerXpop
import com.uduew.sjd.view.xpop.RepaymentDetailsXpop
import com.hjq.bar.OnTitleBarListener
import com.hjq.bar.TitleBar
import com.kongzue.dialogx.dialogs.WaitDialog
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.kunminx.architecture.ui.state.State
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.uduew.sjd.BR
import com.uduew.sjd.R

class RepaymentFragment : BaseFragment() {

    lateinit var mState: RepaymentStates
    private lateinit var mRepaymentRequester: RepaymentRequester
    private lateinit var mAdapter: RepaymentAdapter
    private lateinit var mMessenger: PageMessenger

    override fun initViewModel() {
        mRepaymentRequester = getFragmentScopeViewModel(RepaymentRequester::class.java)
        mState = getFragmentScopeViewModel(RepaymentStates::class.java)
        mMessenger = getApplicationScopeViewModel(PageMessenger::class.java)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mMessenger.output(this) { messages ->
            if (messages.eventId == Messages.EVENT_APPLY_SUCCESS) {
                requestData()
            }
        }

        mRepaymentRequester.result.observe(viewLifecycleOwner) { dataResult: DataResult<AllLoanOrdersApi.ResAllLoanOrdersBean> ->
            mState.refreshState.set(false)
            WaitDialog.dismiss()
            if (!dataResult.responseStatus.isSuccess) {
                ToastUtils.showShortToast(dataResult.responseStatus.responseCode)
                return@observe
            }
            dataResult.result.let {
                mState.list.set(it.mamaguy.thorough)
                mState.orderSize.set(it.mamaguy.thorough.size)
            }
        }
        requestData()
    }

    fun showDetail(
        amountReceived: String,
        interestInterest: String,
        serviceFee: String,
        taxesFees: String,
        channelMount: String,
        totalAmount: String,
        creditService: String
    ) {
        var pop = RepaymentDetailsXpop(
            requireActivity(),
            amountReceived,
            interestInterest,
            serviceFee,
            taxesFees,
            channelMount,
            totalAmount,
            creditService
        )
        pop.setOnAgreeClickListener {
        }
        XPopup.Builder(requireContext())
            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
            .asCustom(pop)
            .show()
    }


    private fun toDetail(bean: AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean?) {
        val bundle = Bundle()
        bundle.putParcelable("orderDetail", bean)
        nav().navigate(R.id.action_navigation_main_to_loan_detail_fragment, bundle)
    }

    override fun getDataBindingConfig(): DataBindingConfig? {
        mAdapter = RepaymentAdapter(requireContext())


        mAdapter.setOnDetailClickListener(object : RepaymentAdapter.OnItemDetailClickListener {
            override fun onItemDetailClick(
                bean: AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean?,
                position: Int
            ) {
                if (!Utils.checkDebounce()) return
                toDetail(bean)
            }

            override fun onItemRepaymentClick(
                bean: AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean?,
                position: Int
            ) {
                if (!Utils.checkDebounce()) return
                toDetail(bean)
            }

            override fun onItemExtensionClick(
                bean: AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean?,
                position: Int
            ) {
                if (!Utils.checkDebounce()) return
                val bundle = Bundle()
                bundle.putParcelable("orderDetail", bean)
                nav().navigate(R.id.action_navigation_main_to_extension_detail_fragment, bundle)
            }
        })

        return DataBindingConfig(R.layout.fragment_repayment, BR.vm, mState)
            .addBindingParam(BR.adapter, mAdapter)
            .addBindingParam(BR.click, Click())
            .addBindingParam(BR.titleBarListener, TitleBarListener())
            .addBindingParam(BR.refreshListener, ListenerRefreshHandler())

    }

    inner class ListenerRefreshHandler : OnRefreshListener {
        override fun onRefresh() {
            requestData()
        }
    }

    inner class TitleBarListener : OnTitleBarListener {
        override fun onLeftClick(titleBar: TitleBar?) {
            super.onLeftClick(titleBar)

        }

        override fun onRightClick(titleBar: TitleBar?) {
            super.onRightClick(titleBar)
            if (!Utils.checkDebounce()) return
            var customerBean = CustomerBean(
                "+86 13240445359",
                "13240445359@163.com",
                "13240445359",
                "13240445359@163.com"
            );
            val mCustomerXpop = CustomerXpop(requireContext(), customerBean)
            XPopup.Builder(requireContext())
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                .asCustom(mCustomerXpop)
                .show()
        }
    }

    fun requestData() {
        if (!Utils.checkDebounce()) return
        val debrief = ArrayList<String>()
        debrief.add("firemen") //待还
        debrief.add("breeks") //逾期
        mRepaymentRequester.request(
            viewLifecycleOwner,
            "", debrief,
            1, 50
        )
    }

    override fun onResume() {
        super.onResume()
        requestData()
    }


    class RepaymentStates : StateHolder() {
        val phylogenic: State<String> = State("")
        var arrayList: ArrayList<String> = ArrayList()
        val refreshState: State<Boolean> = State(true)
        val list: State<ArrayList<AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean>> =
            State<ArrayList<AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean>>(
                ArrayList<AllLoanOrdersApi.ResAllLoanOrdersBean.MamaguyBean.ThoroughBean>()
            )
        val orderSize: State<Int> = State(0)
    }


    inner class Click {

        fun nowApply() {
            mMessenger.input(Messages(Messages.EVENT_SELECT_HOME))
        }
    }
}